<template>
	<div class="addLnventory">
		<el-button type="primary" plain @click="toBack">返回</el-button>
		<h3>库存详情</h3>
		<el-form inline label-position="top" :model="devices" :rules="rules" ref="ruleForm">
			<el-form-item label="产品类型库" style="width: 350px;">
				<el-select v-model="devices.warehouseType" style="width: 100%;">
					<el-option v-for="item in productlibraryList" :label="item.libraryName" :value="item.id"
						:key="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="产品类型" style="width: 350px;">
				<el-select v-model="devices.isProduct" style="width: 100%;">
					<el-option v-for="item in typeListComputed" :label="item.productType" :value="item.id"
						:key="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="产品名称" prop="partName" style="width: 350px;">
				<el-input v-model="devices.partName" placeholder="产品名称">
				</el-input>
			</el-form-item>
			<el-form-item label="产品型号" prop="model" style="width: 350px;">
				<el-input v-model="devices.model" placeholder="产品型号">
				</el-input>
			</el-form-item>
			<el-form-item label="库存数量" style="width: 350px;">
				<el-input v-model="devices.count" type="number" placeholder="库存数量" @input="checkPartCount"
					:disabled="userInfo.roleId != 1">
				</el-input>
			</el-form-item>

			<el-form-item label="单位" style="width: 350px;">
				<el-select v-model="devices.unit" placeholder="请选择计量单位" style="width: 350px;">
					<el-option v-for="item in unitList" :label="item.unitMeasure" :value="item.id"
						:key="item.id"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="产品描述" style="width: 350px;">
				<el-input v-model="devices.devicesDescribe" placeholder="产品描述" type="textarea"
					:autosize="{ minRows: 4, maxRows: 6 }">
				</el-input>
			</el-form-item>
			<el-form-item label="备注" style="width: 350px;">
				<el-input v-model="devices.remark" placeholder="备注" type="textarea"
					:autosize="{ minRows: 4, maxRows: 6 }">
				</el-input>
			</el-form-item>
			<el-form-item label="图片" style="width: 350px;">
				<div class="order-img-div" style="position: relative;margin-right: 10px;"
					v-if="devices.image !== null && devices.image !== ''">
					<el-image :src="READ_IMG_URL + devices.image" class="htimg"
						:preview-src-list="new Array(READ_IMG_URL + devices.image)">
					</el-image>
					<i class="el-icon-close hover-icon" @click="deleteImg"></i>
				</div>
				<img v-else :src="image" class="htimg" @click="selectFile()" />
			</el-form-item>
			<el-form-item label="零件列表" style="width: 100%;"
				v-if="productTypeList.find(item => item.id == devices.isProduct)?.relevance != 'VOID'">
				<el-button type="text" @click="partDialogShow">
					添加零件
				</el-button>
				<div>
					<el-table :data="devices.productPartList" border stripe style="width: 100%" :max-height="500">
						<el-table-column prop="i" fixed="left" label="序号" width="60">
						</el-table-column>
						<el-table-column label="图片" width="120">
							<template slot-scope="scope">
								<el-image :src="READ_IMG_URL + scope.row.image" style="width: 90px; height: 90px;"
									:preview-src-list="new Array(READ_IMG_URL + scope.row.image)">
								</el-image>
							</template>
						</el-table-column>
						<el-table-column prop="partName" label="零件名称" fit>
						</el-table-column>
						<el-table-column prop="model" label="零件型号" fit>
						</el-table-column>
						<el-table-column prop="number" label="组装数量" width="150">
							<template slot-scope="scope">
								<el-input v-model="scope.row.number" type="number"
									@input="checkPartNumber($event, scope.row)">
								</el-input>
							</template>
						</el-table-column>
						<el-table-column prop="unit" label="计量单位" fit>
							<template slot-scope="scope">
								<div v-if="scope.row.unit">
									{{ unitList.find(item => item.id == scope.row.unit).unitMeasure }}
								</div>
								<div v-else>{{ "个" }}</div>
							</template>
						</el-table-column>
						<el-table-column label="操作" width="70">
							<template slot-scope="scope">
								<el-button type="text" @click="deleteParts(scope.row)">
									删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</el-form-item>
			<el-form-item v-if="!readonly" style="width: 100%;">
				<el-button @click="reset">重置</el-button>
				<el-button type="primary" @click="onSubmit">
					{{ devices.id !== null ? '修改' : '提交' }}
				</el-button>
			</el-form-item>
		</el-form>
		<!-- 选择零件弹窗 -->
		<el-dialog style="margin-top:0" :visible.sync="partShow" width="75%" title="选择零件">
			<div style=" width: 100%;display: flex;justify-content: space-between;margin-bottom: 10px;">
				<div>
					<el-button type="primary" @click="confirmParts">确定</el-button>
				</div>
				<!-- 条件查询 -->
				<div>
					<el-input v-model="productPart.partName" placeholder="按名称型号搜索" clearable @change="getPartList"
						style="width: 150px;">
					</el-input>
					<el-select v-model="productPart.warehouseType" style="width: 120px; margin-left: 10px"
						@change="getPartList">
						<el-option label="全部" :value="void 0"></el-option>
						<el-option v-for="item in productlibraryList" :label="item.libraryName" :value="item.id"
							:key="item.id"></el-option>
					</el-select>
					<el-select v-model="productPart.isProduct" @change="getPartList"
						style="width: 120px; margin-left: 10px">
						<el-option label="全部" :value="void 0"></el-option>
						<el-option v-for="item in typelistcomputed.filter(
							item => productTypeList.find(item => item.id == this.devices.isProduct)?.relevance == 'ALL' ||
								productTypeList.find(item => item.id == this.devices.isProduct)?.relevance?.includes(item.id))"
							:label="item.productType" :value="item.id" :key="item.id"></el-option>
					</el-select>
				</div>
			</div>
			<div class="data-table">
				<el-table :data="partList" v-loading="partLoading" border style="width: 100%" :max-height="430"
					:row-key="(row) => row.id" @selection-change="handleSelectionChange" ref="multipleTable">
					<el-table-column type="selection" :reserve-selection="true" width="40" :selectable="selectable">
					</el-table-column>
					<el-table-column prop="i" label="序号" width="50">
					</el-table-column>
					<el-table-column label="产品图片" width="115">
						<template slot-scope="item">
							<el-image style="width: 90px; height: 90px" :src="READ_IMG_URL + item.row.image"
								:preview-src-list="new Array(READ_IMG_URL + item.row.image)">
							</el-image>
						</template>
					</el-table-column>
					<el-table-column prop="partName" label="产品名称" fit>
					</el-table-column>
					<el-table-column prop="model" label="产品型号" fit>
					</el-table-column>
					<el-table-column prop="devicesDescribe" label="产品描述" fit>
					</el-table-column>
					<el-table-column prop="remark" label="备注" fit>
					</el-table-column>
				</el-table>
				<el-pagination background @size-change="partSizeChange" @current-change="partCurrentChange"
					:current-page="productPart.currentPage" :page-sizes="[20, 50, 100]"
					:page-size="productPart.pageSize" layout="total, sizes, prev, pager, next, jumper"
					:total="productPart.total">
				</el-pagination>
			</div>
		</el-dialog>
		<input type="file" id="fileInput" ref="fileInput" style="display: none" @change="handleFileChange" />
	</div>
</template>

<script>
import config from '../../../api/apiURL.js';
import uploadFile from '../../../api/uploadFile.js';
import warehouseApi from "../../../api/warehouse.js";
import unitMeasure from '../../../api/unitMeasure.js';
import productType from '../../../api/productType.js';
import productlibrary from '../../../api/productlibrary.js';
export default {
	data() {
		return {
			READ_IMG_URL: config.READ_IMG_URL,
			userInfo: {},
			image: "",
			selectedFile: null,
			devices: {
				warehouseType: void 0,
				unit: 1,
				id: null,
				isProduct: 1, // 0成品，1零件 
				partName: null, // 产品名称
				model: null, // 产品型号
				count: 0, // 库存数量
				cost: 0.00, // 成本费/采购单价
				process: 0.00, // 加工费
				labour: 0.00, // 人工费
				packing: 0.00, // 打包费
				freight: 0.00, // 运费
				siteFee: 0.00, // 场地费
				price: 0.00, // 销售单价
				isIncludeTax: 1, // 是否含税，0含税，1不含税
				image: null, // 产品图片
				devicesDescribe: null, // 产品描述
				remark: null, // 备注
				productPartList: [], //零件列表
				isUpdatePartList: 1, // 0不修改成品零件列表，1修改成品零件列表
			},
			productPart: {
				partName: null,
				warehouseType: void 0,
				isProduct: 1,
				currentPage: 1,
				pageSize: 50,
				total: 0
			},
			partList: [],
			selectPartList: [],
			partLoading: false,
			partShow: false,
			readonly: false,
			rules: {
				partName: [{
					required: true, message: '请输入产品名称', trigger: 'blur'
				}],
				model: [{
					required: true, message: '请输入产品型号', trigger: 'blur'
				}]
			},
			unitList: new Array(),
			productTypeList: new Array(),
			productlibraryList: new Array()
		}
	},
	created() {
		this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
		this.userInfo.roleId = parseInt(this.userInfo.roleId);
		const id = localStorage.getItem("devicesId");
		if (id) {
			this.devices.id = id
			this.getDevice();
		}
		// 初始化图片
		const url = "https://kris-k.oss-cn-hangzhou.aliyuncs.com/kris/c179093a-41b0-4c70-bc1f-6e5973f35c98-jia.png";
		this.image = url;
	},
	destroyed() {
		localStorage.removeItem("devicesId");
	},
	mounted() {
		this.getUnitList()
		this.getProductTypeList()
		this.getProductlibraryList()
	},
	watch: {
		'devices.isProduct': {
			immediate: true,
			handler() {
				let arr = this.productTypeList.find(item => item.id == this.devices.isProduct)?.relevance
				if (arr == 'ALL') {
					this.productPart.isProduct = 1
				} else if (Array.isArray(arr)) {
					arr.includes(1) ? this.productPart.isProduct = 1 : this.productPart.isProduct = arr[0]
				}
			}
		}
	},
	computed: {
		typeListComputed() {
			return this.devices.warehouseType ?
				this.productTypeList.filter(
					value => this.productlibraryList.find(
						i => i.id == this.devices.warehouseType
					).producttype.split(',').findIndex(item => item == value.id) != -1
				) : this.productTypeList
		},
		typelistcomputed() {
			return this.productPart.warehouseType ?
				this.productTypeList.filter(
					value => this.productlibraryList.find(
						i => i.id == this.productPart.warehouseType
					).producttype.split(',').findIndex(item => item == value.id) != -1
				) : this.productTypeList
		}
	},
	methods: {
		// 返回上个页面
		toBack() {
			this.$router.push({
				path: "/warehouse/lnventory/lnventory"
			})
		},
		// 获取采购订单
		getDevice() {
			const loading = this.$loading({
				lock: true,
				text: 'Loading',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			const data = {
				id: this.devices.id
			}
			warehouseApi.getDevice(data).then(res => {
				if (res.code === 200) {
					res.data.warehouseType = res.data.warehouseType ? Number(res.data.warehouseType) : void 0
					this.devices = {
						...res.data,
						productPartList: []
					}
					if (Array.isArray(res.data.productPartVoList)) {
						this.devices.productPartList = res.data.productPartVoList.map(
							(item, index) => {
								item.i = index + 1;
								return item;
							})
					}
				}
			}).finally(() => {
				loading.close();
			})
		},
		// 打开选择零件弹窗
		partDialogShow() {
			this.getPartList();
			this.partShow = true;
		},
		// 获取零件列表
		getPartList() {
			this.partLoading = true;
			this.partList = [];
			warehouseApi.getDeviceList(this.productPart).then(res => {
				if (res.code === 200) {
					this.productPart.total = res.data.total;
					this.partList = res.data.devicesList.map((item, index) => {
						item.i = (this.productPart.currentPage - 1) * this.productPart.pageSize + index + 1;
						return item;
					})
					// 显示已选择的
					this.$refs.multipleTable.clearSelection();
					if (this.devices.productPartList.length > 0) {
						this.partList.forEach(row => {
							this.devices.productPartList.forEach(part => {
								if (part.partId === row.id) {
									this.$refs.multipleTable.toggleRowSelection(row, true);
								}
							})
						})
					}
					this.partLoading = false;
				}
			})
		},
		// 页码变化
		partCurrentChange(curPage) {
			this.productPart.currentPage = curPage
			this.getPartList()
		},
		// pageSize变化
		partSizeChange(pageSize) {
			this.productPart.pageSize = pageSize
			this.getPartList()
		},
		// 多选零件
		handleSelectionChange(e) {
			this.selectPartList = e;
		},
		// 本成品不可选
		selectable(row, index) {
			return this.devices.id !== row.id;
		},
		// 确认选择
		confirmParts() {
			for (var i = 0; i < this.selectPartList.length; i++) {
				var selectPart = this.selectPartList[i];
				if (this.devices.productPartList.length > 0) {
					let flog = false;
					for (var j = 0; j < this.devices.productPartList.length; j++) {
						var part = this.devices.productPartList[j];
						if (part.partId === selectPart.id) {
							flog = true;
							break;
						}
					}
					if (flog) {
						continue;
					}
				}
				let data = {
					partId: selectPart.id,
					image: selectPart.image,
					partName: selectPart.partName,
					model: selectPart.model,
					number: 1,
					unit: selectPart.unit
				}
				this.devices.productPartList.push(data);
			}
			let newList = this.devices.productPartList.map((item, index) => {
				item.i = index + 1;
				return item;
			})
			this.devices.productPartList = newList;
			this.partShow = false;
		},
		// 删除零件
		deleteParts(item) {
			let newList = this.devices.productPartList.filter(part => part.partId !== item.partId)
			this.devices.productPartList = newList.map((part, index) => {
				part.i = index + 1;
				return part;
			})
			this.partList.forEach(row => {
				if (item.partId === row.id) {
					this.$refs.multipleTable.toggleRowSelection(row, false);
				}
			})
		},

		// 检查输入的库存数量
		checkPartCount(e) {
			// let inputNumber = parseInt(this.devices.count);
			let inputNumber = parseFloat(this.devices.count);
			// 小于0
			if (inputNumber <= 0.00) {
				inputNumber = 0;
			}
			// 使用正则表达式匹配小数点后两位以内的数字或整数
			// let regex = /^\d+(\.\d{1,2})?$/;
			// if (!regex.test(inputNumber)) {
			// 	inputNumber = 0
			// }
			this.devices.count = inputNumber;
		},
		// 检查输入的组装数量
		checkPartNumber(e, item) {
			let inputNumber = parseFloat(item.number);
			// 小于0
			if (inputNumber < 0) {
				inputNumber = 0;
			}
			// 使用正则表达式匹配小数点后两位以内的数字或整数
			// let regex = /^\d+(\.\d{1,2})?$/;
			// if (!regex.test(inputNumber)) {
			// 	inputNumber = 1
			// }
			item.number = inputNumber;
		},
		// 点击上传图片
		selectFile() {
			this.$refs.fileInput.click();
		},
		// 上传oos
		handleFileChange(event) {
			this.selectedFile = event.target.files[0];
			// 上传前验证
			const fileSuffix = this.selectedFile.name.substring(this.selectedFile.name.lastIndexOf(".") + 1);
			const whiteList = ["jpg", "jpeg", "png", "JPG", "JPEG", "PNG"];
			if (whiteList.indexOf(fileSuffix) === -1) {
				this.$message.error("上传文件只能是 jpg、png格式！");
				return;
			}
			const isLt5M = this.selectedFile.size / 1024 / 1024 < 5;
			if (!isLt5M) {
				this.$message.error('上传的图片大小不能超过5MB!');
				return;
			}
			// this.image = URL.createObjectURL(this.selectedFile);
			this.uploadImage();
		},
		//发送上传文件api
		uploadImage() {
			const loading = this.$loading({
				lock: true,
				text: '上传中...',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			let formData = new FormData();
			formData.append("file", this.selectedFile);
			uploadFile.uploadImage(formData).then(res => {
				if (res.code === 200) {
					const url = res.data;
					this.devices.image = url;
					if (this.devices.id !== null && this.devices.id !== '') {
						warehouseApi.changeDeviceImg(this.devices).then(r => {
							if (r.code === 200) {
								this.$message.success("上传成功")
							}
						})
					}
				}
			}).finally(() => {
				loading.close();
			})
		},
		// 删除图片
		deleteImg() {
			if (this.devices.id !== null) {
				this.$confirm('是否要删除此图片？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					// 用户点击了确定按钮时执行的操作
					this.doDeleteImg();
				}).catch(() => {
					// 用户点击了取消按钮时执行的操作，或者点击遮罩层关闭对话框时触发的事件

				});
			} else {
				this.doDeleteImg();
			}
		},
		doDeleteImg() {
			if (this.devices.id !== null) {
				this.devices.image = '';
				const loading = this.$loading({
					lock: true,
					text: '请求中...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				warehouseApi.changeDeviceImg(this.devices).then(res => {
					if (res.code === 200) {
						this.$message.success("删除成功")
					}
				}).finally(() => {
					loading.close();
				})
			} else {
				this.devices.image = '';
			}
		},
		// 提交数据
		onSubmit() {
			this.$refs.ruleForm.validate((valid) => {
				if (!valid) {
					this.$message.error("请将表单填写完整！")
					return false;
				}
				if (this.devices.warehouseType ?
					this.productlibraryList.find(
						i => i.id == this.devices.warehouseType
					).producttype.split(',').findIndex(
						item => this.devices.isProduct == Number(item)
					) == -1 : false) {
					this.$message.error("请选择库中存在的类型")
					return false;
				}
				this.devices.warehouseType = this.devices.warehouseType.toString()
				this.devices.isUpdatePartList = 1;
				if (this.devices.id == null) {
					//新增
					warehouseApi.addDevice(this.devices).then(res => {
						if (res.code === 200) {
							this.$message.success("添加成功")
							this.reset();
						}
					})
				} else {
					//修改
					warehouseApi.updateDevice(this.devices).then(res => {
						if (res.code === 200) {
							this.$message.success("修改成功")
							this.getDevice();
						}
					})
				}
			});
		},
		// 重置
		reset() {
			this.$refs.ruleForm.resetFields();
			this.devices.partName = null; // 产品名称
			this.devices.model = null; // 产品型号
			this.devices.count = 0; // 库存数量
			this.devices.cost = 0.00; // 成本费/采购单价
			this.devices.process = 0.00; // 加工费
			this.devices.labour = 0.00; // 人工费
			this.devices.packing = 0.00; // 打包费
			this.devices.freight = 0.00; // 运费
			this.devices.siteFee = 0.00; // 场地费
			this.devices.price = 0.00; // 销售单价
			this.devices.isIncludeTax = 1; // 是否含税，0含税，1不含税
			this.devices.image = null; // 产品图片
			this.devices.devicesDescribe = null; // 产品描述
			this.devices.remark = null; // 备注
			this.devices.productPartList = []; //零件列表
		},
		getUnitList() {
			unitMeasure.getUnitMeasure().then(res => {
				this.unitList = res.data
			})
		},
		async getProductTypeList() {
			let res = await productType.getProductType()
			res.data.map(item => {
				item.relevance = (item.relevance == "ALL" || item.relevance == "VOID") ? item.relevance : item.relevance.split(",").map(Number)
			})
			this.productTypeList = res.data
		},
		async getProductlibraryList() {
			let res = await productlibrary.getProductlibrary()
			this.productlibraryList = res.data
		}
	}
}
</script>

<style>
.data-table {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	justify-content: center;
	margin-top: 10px;
}

.htimg {
	width: 150px;
	height: 150px;
	object-fit: cover;
	/* 保持原始宽高比，填充容器 */
}

.order-img-div {
	width: 150px;
	height: 150px;
}

.order-img-div:hover .hover-icon {
	display: block;
}

.hover-icon {
	display: none;
	font-size: 24px;
	position: absolute;
	top: 0;
	right: 0;
	color: #ffffff;
	background-color: black;
	opacity: 0.9
}

.hover-icon:hover {
	cursor: pointer;
}
</style>